package com.xoa.service.performance;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.performance.*;
import com.xoa.dao.scoreflowitem.ScoreFlowItemMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.performance.*;
import com.xoa.model.scoreflowitem.ScoreFlowItem;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.service.sms.SmsService;
import com.xoa.service.users.UsersService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.DateFormatUtils;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@RequestMapping("/ScoreFlowService")
public class ScoreFlowService {

    @Autowired
    private ScoreFlowMapper scoreFlowMapper;
    @Autowired
    private ScoreGroupMapper scoreGroupMapper;
    @Autowired
    private ScoreSelfDataMapper scoreSelfDataMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UsersService usersService;

    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    SmsService smsService;

    @Resource
    SysCodeMapper sysCodeMapper;

    @Autowired
    private ScoreFlowItemMapper scoreFlowItemMapper;

    @Autowired
    private ScoreItemMapper scoreItemMapper;

    @Autowired
    private ScoreFlowUsersMapper scoreFlowUsersMapper;

    @Autowired
    private ScoreFlowUserService scoreFlowUserService;
    @Autowired
    private DepartmentMapper departmentMapper;
    /**
     * 郭心雨
     * 2018.06.22
     * 添加考核任务
     * @param scoreFlow
     * @return
     */
    public ToJson addScoreFlow(ScoreFlowWithBLOBs scoreFlow,HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

        ToJson toJson = new ToJson();
        if(scoreFlow.getBeginDateStr()!=null){
            scoreFlow.setBeginDate(DateFormat.getDates(scoreFlow.getBeginDateStr()));
        }
        if(scoreFlow.getEndDateStr()!=null){
            scoreFlow.setEndDate(DateFormat.getDates(scoreFlow.getEndDateStr()));
        }
        scoreFlow.setFlowFlag("1");
        scoreFlow.setCreateUserId(user.getUserId());
        //新增时加上考核部门
        StringBuffer deptIds = new StringBuffer();
        StringBuffer userIds = new StringBuffer();//重新组织userId，排序后位置会发生改变
        List<Users> usersByUserIds = usersMapper.getUsersByUserIdsOrderByDeptId(scoreFlow.getParticipant().split(","));
        for (Users list:usersByUserIds){
            deptIds.append(list.getDeptId()+",");
            userIds.append(list.getUserId()+",");
        }
        scoreFlow.setParticipant(userIds.toString());
        scoreFlow.setParticipantDept(deptIds.toString());
        int count=scoreFlowMapper.insertSelective(scoreFlow);
        if (count>0){

            String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
            //sendSms(user.getUserId(),scoreFlow.getParticipant(),request.getParameter("remind"),request.getParameter("smsRemind"),sqlType);
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }
    /**
     * 郭心雨
     * 2018.06.22
     * 删除考核任务
     * @param flowId
     * @return
     */
    public ToJson delScoreFlow(Integer flowId) {
        ToJson toJson = new ToJson();
        int count=scoreFlowMapper.deleteByPrimaryKey(flowId);
        scoreFlowUsersMapper.deleteByFlowId(flowId);
        scoreFlowItemMapper.deleteByFlowId(flowId);
        if (count>0){
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }
    /**
     * 郭心雨
     * 2018.06.22
     * 修改考核任务
     * @param scoreFlow
     * @return
     */
    public ToJson modifyScoreFlow(ScoreFlowWithBLOBs scoreFlow) {
        ToJson toJson = new ToJson();
        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectScoreFlowById(scoreFlow.getFlowId());
        // 匹配删除人员
        String participant = scoreFlowWithBLOBs.getParticipant();
        if(!StringUtils.checkNull(participant)){
            List<String> strings = new ArrayList<>(Arrays.asList(participant.split(",")));
            Iterator<String> it = strings.iterator();
            String participant1 = scoreFlow.getParticipant();
            if(!StringUtils.checkNull(participant1)){
                while(it.hasNext()){
                    String next = it.next();
                    for (String newUserId:participant1.split(",")){
                        if(next.equals(newUserId)){
                            it.remove();
                        }
                    }
                }
            }
            for (String userId:strings) {
                scoreFlowUsersMapper.deleteByFlowAndUserId(scoreFlow.getFlowId(),userId);
            }
        }
        //更新时加上考核部门
        StringBuffer sb = new StringBuffer();
        List<Users> usersByUserIds = usersMapper.getUsersByUserIds(scoreFlow.getParticipant().split(","));
        for (Users list:usersByUserIds){
            sb.append(list.getDeptId()+",");
        }
        scoreFlow.setParticipantDept(sb.toString());
        int count=scoreFlowMapper.updateByPrimaryKeySelective(scoreFlow);
        if (count>0){
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }


    /**
     * 郭心雨
     * 2018.06.22
     * 动态模糊查询考核任务
     * @param scoreFlow
     * @param page
     * @param pageSize
     * @param useFlag
     * @return
     */
    public ToJson selAllScoreFlow(HttpServletRequest request,ScoreFlowWithBLOBs scoreFlow, Integer page, Integer pageSize, Boolean useFlag ,String flowFlag2,String ifAssessment) {
        ToJson<ScoreFlowWithBLOBs> toJson =new ToJson();
        //获取当前登录的用户
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        /*scoreFlow.setRankman(user.getUserId());
        scoreFlow.setParticipant(user.getUserId());
        scoreFlow.setViewUserId(user.getUserId());*/
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);

        if(!StringUtils.checkNull(flowFlag2)&&"1".equals(flowFlag2)){
            map.put("flowFlag2",flowFlag2);
        }

        if(!StringUtils.checkNull(ifAssessment)&&"1".equals(ifAssessment)){
            scoreFlow.setRankman(user.getUserId());
        }

        scoreFlow.setCreateUserId(user.getUserId());
        map.put("scoreFlow", scoreFlow);

//        //判断获取到的当前用户是否为空
//        if(user!=null){
//                scoreFlow.setRankman(user.getUserId());//获取当前登录用户的userId
//                scoreFlow.setParticipant(user.getUserId());//获取当前登录用户的userId
//                scoreFlow.setViewUserId(user.getUserId());//获取当前登录用户的userId
//
//
//        }
        //查出考核任务
        List<ScoreFlowWithBLOBs> scoreFlowList=scoreFlowMapper.selectAllScoreFlow(map);
        if (scoreFlowList!=null){
            toJson.setTotleNum(pageParams.getTotal());
            toJson.setFlag(0);
            toJson.setMsg("ok");
            for(ScoreFlowWithBLOBs scoreFlows:scoreFlowList){
                //获取待考核人员
                List<String> allAssessorByStatus = scoreFlowUsersMapper.getAllAssessorByStatus(scoreFlows.getFlowId());
                StringBuffer str=new StringBuffer();
                for (String userId: allAssessorByStatus) {
                    str.append(userId+",");
                }
                if(!StringUtils.checkNull(str.toString())){
                    scoreFlows.setAssessorName(usersService.getUserNamesByUserIds(str.toString()));
                }
                // 查看问卷名称
                Integer groupId = scoreFlows.getGroupId();
                ScoreGroupWithBLOBs scoreGroupWithBLOBs = scoreGroupMapper.selectByPrimaryKey(groupId);
                if(scoreGroupWithBLOBs!=null){
                    scoreFlows.setGroupName(scoreGroupWithBLOBs.getGroupName());
                }
                //转换日期格式
                if(scoreFlows.getBeginDate()!=null) {
                    scoreFlows.setBeginDateStr(DateFormat.getDatestr(scoreFlows.getBeginDate()));//考核生效日期
                }
                if(scoreFlows.getEndDate()!=null) {
                    scoreFlows.setEndDateStr(DateFormat.getDatestr(scoreFlows.getEndDate()));//考核终止日期
                }
                if(scoreFlows.getSendTime()!=null){
                    scoreFlows.setEsendTimeStr(DateFormat.getDatestr(scoreFlows.getSendTime()));//考核任务新建日期
                }
                //查看被考核人姓名
                if (scoreFlows.getParticipant() != null) {
                    String userName = "";
                    String[] userIds = scoreFlows.getParticipant().split(",");
                    List<Users> users = usersMapper.getUsersByUserIdsOrder(userIds);

                    for (int i = 0; i < users.size(); i++) {
                        userName += users.get(i).getUserName() + ",";
                    }
                    if (!userName.equals("") && userName != null) {
                        scoreFlows.setParticipantName(userName);
                    } else {
                        scoreFlows.setParticipantName("用户信息不存或已删除");
                    }
                }

            }
            toJson.setObj(scoreFlowList);
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }

    public ToJson selectCycle(HttpServletRequest request, String type) {
        ToJson json = new ToJson();
        //最新添加先显示
        List<SysCode> assessment_cycle = sysCodeMapper.getSysCodeDesc("ASSESSMENT_CYCLE");
        List<SysCode> result = new ArrayList<>();
        for (SysCode list:assessment_cycle){
            if ("目标薪酬".equals(type)){//领导
                if (list.getCodeName().contains("半年")){
                    result.add(list);
                }
            }else if("岗位薪酬".equals(type)){
                if (list.getCodeName().contains("季度")){
                    result.add(list);
                }
            }
        }
        json.setFlag(0);
        json.setObj(result);
        return json;
    }

    public ToJson updateDept(HttpServletRequest request, Integer flowId, Integer deptId, String userId) {
        ToJson json = new ToJson();
        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(flowId);
        String[] userArr = scoreFlowWithBLOBs.getParticipant().split(",");
        String[] deptArr = scoreFlowWithBLOBs.getParticipantDept().split(",");
        int num = 0;
        for (String list:userArr){
            if (list.equals(userId)){
                deptArr[num] = String.valueOf(deptId);
            }
            num += 1;
        }
        StringBuffer sb = new StringBuffer();
        for (String list1:deptArr){
            sb.append(list1+",");
        }
        scoreFlowWithBLOBs.setParticipantDept(sb.toString());
        scoreFlowMapper.updateByPrimaryKeySelective(scoreFlowWithBLOBs);
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }

    /**
     * 郭心雨
     * 2018.07.06
     * 根据id克隆
     * @param flowId
     * @return
     */
    public ToJson kelong(Integer flowId) {
        ToJson toJson = new ToJson();
        ScoreFlowWithBLOBs scoreFlow=scoreFlowMapper.selectScoreFlowById(flowId);
        if (scoreFlow!=null){
            // 查询出原来的所有人员设置
            Map<String,Object> map = new HashMap<>();
            map.put("scoreFlowId",scoreFlow.getFlowId());
            List<ScoreFlowUsers> scoreFlowUsers = scoreFlowUsersMapper.selectFlowUsers(map);

            scoreFlow.setFlowId(null);
            scoreFlow.setFlowFlag("1");
            int count=scoreFlowMapper.insertSelective(scoreFlow);

            for (ScoreFlowUsers scoreFlowUser:scoreFlowUsers) {
                scoreFlowUser.setScoreFlowId(scoreFlow.getFlowId());
                scoreFlowUser.setId(null);
                scoreFlowUser.setStatus(0);
                scoreFlowUser.setScore(null);
                scoreFlowUsersMapper.insertSelective(scoreFlowUser);
            }

            if (count>0){
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }

        return toJson;
    }

    /**
     * 郭心雨
     * 2018.07.06
     * 根据userId查看用户信息
     * @param userId
     * @return
     */
    public ToJson selUserByUserId(String userId) {
        ToJson toJson = new ToJson();
        if(!StringUtils.checkNull(userId)){
            String[] userIds=userId.split(",");
            List<Users> usersList=usersMapper.getUsersByUserIds(userIds);
            if (usersList!=null){
                toJson.setObj(usersList);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }
        }
        return toJson;
    }

    public ToJson stopNow(HttpServletRequest request,Integer flowId, String flowFlag, String remind,String tuisong) {

        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

        String sqlType = (String) request.getSession().getAttribute("loginDateSouse");

        ToJson toJson = new ToJson();
        ScoreFlowWithBLOBs scoreFlow=new ScoreFlowWithBLOBs();
        scoreFlow.setFlowId(flowId);
        scoreFlow.setFlowFlag(flowFlag);
        //flowFlag：0生效，2终止    传0代表恢复生效，终止时间为空，传1代表立即终止，终止时间为当前时间
        // 根据2020 08 28的需求 舍弃掉设置时间的逻辑
        /*if (flowFlag.equals("2")){
            scoreFlow.setEndDate(new Date());
        }else if (flowFlag.equals("0")){
            scoreFlow.setEndDate(null);
        }*/
        int count=scoreFlowMapper.updateFlowFlag(scoreFlow);

        // 如果是设置生效的话 进行发送事务提醒
        if (flowFlag.equals("0")){
            ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectScoreFlowById(flowId);
            List<String> strings = scoreFlowUsersMapper.selectAllAssessors(flowId);
            StringBuilder userIds = new StringBuilder();
            strings.forEach(userId -> {
                userIds.append(userId).append(",");
            });
            // 给考核人发送事务提醒
            addSmsRemind(scoreFlowWithBLOBs, user.getUserId(), userIds.toString(),tuisong, remind, sqlType);
        }


        if (count>0){
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }
    public ToJson<ScoreFlowWithBLOBs> selScoreFlow(int flowId){
        ToJson<ScoreFlowWithBLOBs> toJson=new ToJson<>();
        try{
            List<ScoreFlowWithBLOBs> list= scoreFlowMapper.selectScoreFlowByFlowId(flowId);
            //处理时间
            for(ScoreFlowWithBLOBs scoreFlowWithBLOBs:list){

                scoreFlowWithBLOBs.setBeginDateStr(getTimeStr(scoreFlowWithBLOBs.getBeginDate()));
                scoreFlowWithBLOBs.setEndDateStr(getTimeStr(scoreFlowWithBLOBs.getEndDate()));
                //被考核人
                if(!StringUtils.checkNull(scoreFlowWithBLOBs.getParticipant())){
                    List<Users> users = usersMapper.getUsersByUserIdsOrder(scoreFlowWithBLOBs.getParticipant().split(","));
                    String bkhrname="";
                    for(Users users1:users){
                        bkhrname += users1.getUserName()+",";
                    }
                    scoreFlowWithBLOBs.setParticipantName(bkhrname);
                }
                //任务查看者
                if(!StringUtils.checkNull(scoreFlowWithBLOBs.getViewUserId())){
                    List<Users> users = usersMapper.getUsersByUserIdsOrder(scoreFlowWithBLOBs.getViewUserId().split(","));
                    String rwckzname="";
                    for(Users users1:users){
                        rwckzname += users1.getUserName()+",";
                    }
                    scoreFlowWithBLOBs.setViewUserName(rwckzname);
                }
                if(!StringUtils.checkNull(scoreFlowWithBLOBs.getAssessmentUnit())){
                    scoreFlowWithBLOBs.setAssessmentUnitName(departmentMapper.getDeptById(Integer.parseInt(scoreFlowWithBLOBs.getAssessmentUnit())).getDeptName());
                }
            }
            toJson.setObj(list);
            toJson.setMsg("true");
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    public String getTimeStr(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String re_time = "";
        try {
            re_time = sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return re_time;
    }

    /**
     * 查询当前用户名字
     * @param uId
     * @return
     */
    public List<ScoreFlowWithBLOBs> getUserName(String uId){
        List<ScoreFlowWithBLOBs> scoreFlowList=scoreFlowMapper.getHrStaffContractList(uId);
        Map<String, Object> map = new HashMap<String, Object>();
        if (scoreFlowList!=null) {
            for (ScoreFlowWithBLOBs scoreFlows : scoreFlowList) {
                //查看问卷名称
                Integer groupId = scoreFlows.getGroupId();
                ScoreGroupWithBLOBs scoreGroupWithBLOBs = scoreGroupMapper.selectByPrimaryKey(groupId);
                if(scoreGroupWithBLOBs!=null){
                    scoreFlows.setGroupName(scoreGroupWithBLOBs.getGroupName());
                }


                //转换日期格式
                if (scoreFlows.getBeginDate() != null) {
                    scoreFlows.setBeginDateStr(DateFormat.getDatestr(scoreFlows.getBeginDate()));//考核生效日期
                }
                if (scoreFlows.getEndDate() != null) {
                    scoreFlows.setEndDateStr(DateFormat.getDatestr(scoreFlows.getEndDate()));//考核终止日期
                }
                if (scoreFlows.getSendTime() != null) {
                    scoreFlows.setEsendTimeStr(DateFormat.getDatestr(scoreFlows.getSendTime()));//考核任务新建日期
                }

                //查看被考核人姓名
                if (scoreFlows.getParticipant() != null) {
                    String userName = "";
                    String[] userIds = scoreFlows.getParticipant().split(",");
                    List<Users> users = usersMapper.getUsersByUserIds(userIds);

                    for (int i = 0; i < users.size(); i++) {
                        userName += users.get(i).getUserName() + ",";
                    }
                    if (!userName.equals("") && userName != null) {
                        scoreFlows.setParticipantName(userName);
                    } else {
                        scoreFlows.setParticipantName("用户信息不存或已删除");
                    }
                }
            }
        }
        return scoreFlowList;
    }

    public ToJson<ScoreFlowItem> selScoreFlowDetail(Integer flowId,Integer groupId,PageParams pageParams){
        ToJson<ScoreFlowItem> json = new ToJson<ScoreFlowItem>();

        Map<String,Object> map = new HashMap<>();
        map.put("flowId",flowId);
        map.put("groupId",groupId);
        if(pageParams!=null&&pageParams.getPage()!=null){
            map.put("page",pageParams);
        }

        List<ScoreFlowItem> scoreFlowItems = scoreFlowItemMapper.selScoreFlowDetails(map);

        json.setObj(scoreFlowItems);
        json.setFlag(0);
        json.setTotleNum(pageParams.getTotal());

        return json;
    }

    // 查询自评列表
    public ToJson selScoreSelfData(HttpServletRequest request, PageParams pageParams,String scoreSelfFlag){
        ToJson json = new ToJson();

        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("userId",user.getUserId());
        map.put("scoreSelfFlag",scoreSelfFlag);
        map.put("page",pageParams);

        // 查询自评数据
        List<ScoreFlowWithBLOBs> scoreFlowWithBLOBs = scoreFlowMapper.selScoreSelfData(map);


        json.setObj(scoreFlowWithBLOBs);
        json.setFlag(0);
        json.setMsg("ok");

        return json;
    }

    /**
     * @接口说明: 查询当前用户需要评测的任务
     * @日期: 2020/7/20
     * @作者: 张航宁
     */
    public BaseWrapper selMyFlows(HttpServletRequest request, PageParams pageParams){
        BaseWrapper baseWrapper = new BaseWrapper();

        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        String status = request.getParameter("status");
        Map<String,Object> map = new HashMap<>();
        map.put("page",pageParams);
        map.put("userId",user.getUserId());
        map.put("nowDate",new Date());
        map.put("status",status);
        List<ScoreFlowWithBLOBs> scoreFlowWithBLOBs = scoreFlowMapper.selMyFlows(map);
        for (ScoreFlowWithBLOBs scoreFlow:scoreFlowWithBLOBs) {
            ScoreGroupWithBLOBs scoreGroupWithBLOBs = scoreGroupMapper.selectByPrimaryKey(scoreFlow.getGroupId());
            if(scoreGroupWithBLOBs!=null){
                scoreFlow.setGroupName(scoreGroupWithBLOBs.getGroupName());
            }
            if(!StringUtils.checkNull(scoreFlow.getAssessmentUnit())){
                scoreFlow.setAssessmentUnitName(departmentMapper.getDeptById(Integer.parseInt(scoreFlow.getAssessmentUnit())).getDeptName());
            }
        }

        baseWrapper.setData(scoreFlowWithBLOBs);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        baseWrapper.setTotleNum(pageParams.getTotal());

        return baseWrapper;
    }

    /**
     * @接口说明: 根据任务id查询试卷下的指标集和项目分类
     * @日期: 2020/7/21
     * @作者: 张航宁
     */
    public BaseWrapper selPaperDetail(HttpServletRequest request, Integer flowId){
        BaseWrapper baseWrapper = new BaseWrapper();
        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(flowId);
        if(scoreFlowWithBLOBs!=null){
            // 查询考核指标集
            ScoreGroupWithBLOBs scoreGroup = scoreGroupMapper.selectByPrimaryKey(scoreFlowWithBLOBs.getGroupId());

            if(scoreGroup!=null){
                // 查询考核类型
                List<ScoreGroupWithBLOBs> scoreGroupTypes = scoreGroupMapper.selectByTypeId(String.valueOf(scoreGroup.getGroupId()));
                for(ScoreGroupWithBLOBs scoreGroupType:scoreGroupTypes){
                    // 查询考核明细
                    List<ScoreItem> scoreItems = scoreItemMapper.selectByTypeId(scoreGroupType.getGroupId());
                    scoreGroupType.setScoreItems(scoreItems);
                }
                scoreGroup.setGroupTypes(scoreGroupTypes);


                // 查询该考核下的人员
                BaseWrapper baseWrapper1 = scoreFlowUserService.selByAssessor(request, flowId);
                if(baseWrapper1.isFlag()){
                    List<ScoreFlowUsers> data = (List<ScoreFlowUsers>) baseWrapper1.getData();
                    scoreGroup.setScoreFlowUsers(data);
                }
            }
            baseWrapper.setData(scoreGroup);
        }

        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @接口说明: 评价保存接口
     * @日期: 2020/7/21
     * @作者: 张航宁
     */
    public BaseWrapper setFlowItem(HttpServletRequest request,ScoreFlowItem scoreFlowItem,String userScores,Integer status){
        BaseWrapper baseWrapper = new BaseWrapper();

        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

        Integer flowId = scoreFlowItem.getFlowId();

        // 查询出所有的考核项目和权重 用来下面算总分时候的计算
        Map<Integer,Double> typeWeightMap = new HashMap<>();
        Map<Integer,Integer> itemAndTypeMap = new HashMap<>();
        Map<Integer,Double> itemWeightMap = new HashMap<>();


        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(flowId);
        if(scoreFlowWithBLOBs!=null){
            // 查询考核指标集
            ScoreGroupWithBLOBs scoreGroup = scoreGroupMapper.selectByPrimaryKey(scoreFlowWithBLOBs.getGroupId());

            if(scoreGroup!=null){
                scoreFlowItem.setGroupId(scoreFlowWithBLOBs.getGroupId());
                // 查询考核类型
                List<ScoreGroupWithBLOBs> scoreGroupTypes = scoreGroupMapper.selectByTypeId(String.valueOf(scoreGroup.getGroupId()));
                for(ScoreGroupWithBLOBs scoreGroupType:scoreGroupTypes){
                    // 查询考核明细
                    typeWeightMap.put(scoreGroupType.getGroupId(),scoreGroupType.getWeight());
                    List<ScoreItem> scoreItems = scoreItemMapper.selectByTypeId(scoreGroupType.getGroupId());
                    for (ScoreItem scoreItem:scoreItems) {
                        itemAndTypeMap.put(scoreItem.getItemId(),scoreGroupType.getGroupId());
                        itemWeightMap.put(scoreItem.getItemId(),scoreItem.getWeight());
                    }
                }
            }
        }

        // userScores的格式为 scoreFlowUser中的id*明细id_分数|明细id2_分数,scoreFlowUser中的id2*明细id_分数|明细id2_分数
        if(!StringUtils.checkNull(userScores)){
            // 先删除一次数据
            scoreFlowItemMapper.deleteByFlowAndExaminer(flowId,user.getUserId());
            // 用,拆分出所有的用户和他的考试分数
            String[] userScoreInfo = userScores.split(",");
            for (String userScore:userScoreInfo) {
                // 用*拆分被考核人的userId和考核分数
                String[] split = userScore.split("\\*");
                if(split.length>1){
                    // 被考核人的userId
                    String ids = split[0];
                    if(!StringUtils.checkNull(ids)){
                        String[] split1 = ids.split("&");
                        Double scoreCount = 0.0;
                        for (int i = 0; i < split1.length; i++) {
                            String id = split1[i];
                            // 查询出scoreFlowUser关联数据 用来获取userId和之后进行总分数据更新
                            ScoreFlowUsers scoreFlowUsers = scoreFlowUsersMapper.selectByPrimaryKey(Integer.valueOf(id));
                            // 如果有多条 就只保存一次分数
                            if(i == 0){
                                scoreCount = 0.0;
                                String userId = scoreFlowUsers.getUserId();
                                scoreFlowItem.setBeikao(userId);
                                Users users = usersMapper.SimplefindUsersByuserId(userId);
                                if(users!=null){
                                    scoreFlowItem.setBeikaoStr(users.getUserName());
                                }
                                // 被考核人的明细id和分数 格式为 id_分数|id2_分数2
                                String scores = split[1];
                                if(!StringUtils.checkNull(scores)){
                                    // 拆分出每一项的考核明细的id和分数
                                    for (String score:scores.split("\\|")) {
                                        String[] s = score.split("_");
                                        Integer itemId = Integer.valueOf(s[0]);
                                        scoreFlowItem.setItemId(itemId);
                                        scoreFlowItem.setGrade(s[1]);

                                        // 设置默认数据
                                        scoreFlowItem.setSelfFlag(1);
                                        scoreFlowItem.setExaminer(user.getUserId());
                                        scoreFlowItem.setExaminerStr(user.getUserName());

                                        scoreFlowItemMapper.insertSelective(scoreFlowItem);

                                        Double grade = Double.parseDouble(s[1]);
                                        // 获取考核明细的分类id  用来获取分类的权重
                                        Integer typeId = itemAndTypeMap.get(itemId);
                                        // 分类权重
                                        Double typeWeight = typeWeightMap.get(typeId);
                                        // 明细权重
                                        Double itemWeight = itemWeightMap.get(itemId);
                                        // 计算分数 并增加进总分
                                        scoreCount= scoreCount + (grade*typeWeight*itemWeight);

                                    }
                                }
                            }
                            // 判断是保存还是提交 如果是提交的话 计算总分并保存
                            // 保存默认为0 status==1是正常提交
                            if(status!=null&&status==1){
                                // 判断时间是否超过最终的限制时间 如果超过的话 状态改为2 超时提交
                                if(scoreFlowWithBLOBs != null&& scoreFlowWithBLOBs.getEndDate().getTime()<new Date().getTime()){
                                    status = 2;
                                }
                                scoreFlowUsers.setScore(new BigDecimal(scoreCount).setScale(2, RoundingMode.UP).doubleValue());
                                scoreFlowUsers.setStatus(status);
                                scoreFlowUsers.setSubmissionTime(new Date());//提交时间。获取当前系统时间
                                scoreFlowUsersMapper.updateByPrimaryKeySelective(scoreFlowUsers);
                                // 初始化
                                status = 1;
                            }

                        }
                    }
                }
            }
        }

        Map<String,Object> map = new HashMap<>();
        map.put("scoreFlowId",flowId);
        int paperCount = scoreFlowUsersMapper.selectCount(map);
        map.put("sql","and status != 0");
        int downCount = scoreFlowUsersMapper.selectCount(map);
        if(paperCount==downCount){
            stopNow(request,flowId,"3",null,null);
        }


        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);

        return baseWrapper;
    }

    public  void addSmsRemind(ScoreFlowWithBLOBs scoreFlowWithBLOBs, String fromId, String toUserIds, final String tuisong, final String remind, final String sqlType){
        if(StringUtils.checkNull(remind)||"0".equals(remind)){
            return;
        }
        if(StringUtils.checkNull(toUserIds)){
            return;
        }
        //选择人员
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa"+sqlType);
                SmsBody smsBody=new SmsBody();
                smsBody.setFromId(fromId);

                List<String> toUserIdsList = Arrays.asList(toUserIds.split(","));
                Iterator<String> iterator = toUserIdsList.iterator();
                StringBuilder userIds = new StringBuilder();
                while (iterator.hasNext()){
                    String next = iterator.next();
                    if(!StringUtils.checkNull(next)){
                        Integer smsId = smsService.selectSmsId(next, "/ScoreFlowController/kaoheList?flowId=" + scoreFlowWithBLOBs.getFlowId() + "&type=1");
                        if(smsId==null||smsId==0){
                            userIds.append(next).append(",");
                        }
                    }
                }


                Integer sendTime=0;
                if(scoreFlowWithBLOBs.getBeginDate()!=null){
                    try {
                        sendTime= DateFormatUtils.getNowDateTime(DateFormatUtils.formatDate(scoreFlowWithBLOBs.getBeginDate()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }


                smsBody.setSendTime(sendTime);
                SysCode sysCode=new SysCode();
                sysCode.setCodeName("考核");
                sysCode.setParentNo("SMS_REMIND");

                if(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode)!=null){
                    smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
                }

                String context = "您有新的360考核任务需要进行评分，考核任务名称："+scoreFlowWithBLOBs.getFlowTitle();
                smsBody.setContent(context);
                smsBody.setRemindUrl("/ScoreFlowController/kaoheList?flowId="+scoreFlowWithBLOBs.getFlowId()+"&type=1");
                smsService.saveSms(smsBody,userIds.toString(),remind,tuisong,"360考核提醒",context,sqlType);
            }
        });

    }
}
